package handler

import (
	"fmt"
	"net/http"
	"time"
	"togethorGo/db"
	"togethorGo/util"
)

const (
	salt = "beatful"
)

var (
	users  = make(map[string]string)
	tokens = make(map[string]string)
)

// HandleUserInfo : 获取用户信息
func HandleUserInfo(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username := r.Form.Get("username")
	password := r.Form.Get("password")
	data, _ := db.HandleUserInfo(username, password)
	w.Write(util.NewRespMsg(0, "用户信息", data).JSONBytes())
}

//HandleUserRegister : 用户注册
func HandleUserRegister(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	r.ParseForm()
	username := r.Form.Get("username")
	password := r.Form.Get("password")

	//密码加密
	encpasswd := util.Sha1([]byte(password + salt))
	//将用户信息写入数据库
	fmt.Printf("用户注册[%s] [%s] [%s] \n", username, password, encpasswd)
	users[username] = encpasswd
	w.Write(util.NewRespMsg(0, "注册成功", nil).JSONBytes())
}

// HandleUserLogin : 获取登陆
func HandleUserLogin(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username := r.Form.Get("username")
	password := r.Form.Get("password")
	encpassword := util.Sha1([]byte(password + salt))
	//校验用户名和密码是否正确
	v, ok := users[username]
	if ok != true {
		w.Write(util.NewRespMsg(-1, "用户名不存在", nil).JSONBytes())
		return
	}
	if v != encpassword {
		w.Write(util.NewRespMsg(-1, "密码错误", nil).JSONBytes())
		return
	}

	token := GenToken(username)
	tokens[username] = token
	//返回token
	w.Write(util.NewRespMsg(0, "登陆成功", struct {
		Token string
	}{
		Token: token,
	}).JSONBytes())

}

// HandleUserLogout : 用户登出
func HandleUserLogout(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username := r.Form.Get("username")
	//删除tokens中对应的用户
	delete(tokens, username)
	w.Write(util.NewRespMsg(0, "用户退出", nil).JSONBytes())
}

// HandleUserUnregister : 注销用户
func HandleUserUnregister(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username := r.Form.Get("username")
	delete(users, username)
	w.Write(util.NewRespMsg(0, "用户注销", nil).JSONBytes())
}

//IsTokenValid ：校验token
func IsTokenValid(username, token string) bool {
	//后八位是token过期时间
	ts := token[32:]
	t := util.Str16toInt(ts)
	if t < time.Now().Unix() { //判断过期时间是否小于当前时间
		fmt.Printf("token is expired %d\n", t)
		return false
	}
	tokenSer, ok := tokens[username]
	if !ok {
		fmt.Printf("No have this %s user token\n", username)
		return false
	}
	if token != tokenSer {
		fmt.Printf("token 不一致 token=[%s] tokenSer=[%s]\n", token, tokenSer)
		return false
	}

	return true
}

//GenToken : 生成token
func GenToken(username string) string {
	//过期时间3600s
	expired := time.Now().Add(time.Second * 3600).Unix()
	ts := fmt.Sprintf("%x", expired)
	tokenprefix := util.MD5([]byte(username + ts + "_tokensalt"))
	return tokenprefix + ts[:8]
}
